<template>
  <div class="video-container">
    <video class="video" src="/歌.mp3" controls autoplay></video>
  </div>

  <div class="o">
    <div class="scroll" @wheel="handleScroll">
      <!-- class="active" -->
      <div :class="activeIndex == index ? 'active' : ''" class="item" v-for="(item, index) in lyr" :key="item.time">
        {{ item.words }}
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { lyr } from "@/utils/lyr/index"
import { onMounted, ref } from "vue";

// 寻找当前播放的歌词索引
const findIndex = () => {
  const currentTime = document.querySelector(".video")?.currentTime;
  for (let i = 0; i < lyr.length; i++) {
    if (currentTime < lyr[i].time) {
      return i - 1;
    }
  }
  return lyr.length - 1;
}

let activeIndex = ref(0)
const setY = () => {
  
  const index = findIndex();

  if (index == activeIndex.value) return;

  // 计算偏移量 是文本处展示的位置
  // 获取盒子高度
  // 计算当前歌词内容的偏移
  const contentY = index * lineHeight;
  let offset = contentY - boxHeight / 2;
  const maxOffset = totalHeight - boxHeight;
  if (offset < 0) {
    offset = 0;
  } else if (offset > maxOffset) {
    offset = maxOffset;
  }
  scroll.style.transform = `translateY(-${offset}px)`;
  activeIndex.value = index;
}

let boxHeight: any;
let scroll: any;
let totalHeight: any;
let lineHeight: any;
let currentOffset = 0; // 当前滚动容器的偏移量

// 获取每一行的高度
onMounted(() => {
  // 获取盒子高度
  boxHeight = document.querySelector(".o")!.clientHeight;
  // 获取歌词总高度
  scroll = document.querySelector(".scroll");
  totalHeight = scroll?.clientHeight;
  // 获取每一行的高度
  lineHeight = totalHeight / scroll?.children.length;
  console.log(lineHeight, '-====');

  document.querySelector('.video')?.addEventListener('timeupdate', setY);
})

// 处理鼠标滚轮事件
const handleScroll = (event: WheelEvent) => {
  const delta = event.deltaY; // 获取滚动方向
  console.log(delta,'delta');
  currentOffset += delta; // 更新当前偏移量
  const maxOffset = totalHeight - boxHeight;
  if (currentOffset < 0) {
    currentOffset = 0;
  } else if (currentOffset > maxOffset) {
    currentOffset = maxOffset;
  }
  scroll.style.transform = `translateY(-${currentOffset}px)`;
};

</script>

<style lang="scss" scoped>
.video-container {
  display: flex;
  justify-content: center;
  align-items: center;
}
.video {
  width: 450px;
  height: 120px;
}

.o {
  height: 500px;
  overflow: hidden;
  border: 1px solid pink;
  .scroll {
    &>div {
      height: 50px;
      line-height: 50px;
      text-align: center;
      transform: scale(0.8);
      transition: 0.2s;
      &.active {
        color: orange;
        transform: scale(1);
      }
      // background-color: #ccc;
    }
  }
}
</style>